package middleware

import (
	"bytes"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/util/gconv"
	"io/ioutil"
	"rock/customer/initParam"
	"strings"
	"time"
)

// 请求进入日志
func RequestInLog(c *gin.Context) {
	//lib.HttpJSON(lib.NewTrace(), queryUrl, paramJsonStr, 60*1000, nil)
	traceContext := lib.NewTrace()
	if traceId := c.Request.Header.Get("com-header-rid"); traceId != "" {
		traceContext.TraceId = traceId
		//Timeout(c, 3*time.Second, traceId, 30*time.Second)
	}
	if spanId := c.Request.Header.Get("com-header-spanid"); spanId != "" {
		traceContext.SpanId = spanId
	}

	c.Set("startExecTime", time.Now())
	c.Set("trace", traceContext)

	resp := c.Request
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body)) // Write body back

	if initParam.BaseConf.DebugMode == "debug" {
		lib.Log.TagInfo(traceContext, "_com_request_in", map[string]interface{}{
			"uri":    c.Request.RequestURI,
			"method": c.Request.Method,
			"args":   c.Request.PostForm,
			"body":   string(body),
			"from":   c.ClientIP(),
		})
	}
}

// 请求输出日志
func RequestOutLog(c *gin.Context) {
	// after request
	endExecTime := time.Now()
	response, _ := c.Get("response")
	st, _ := c.Get("startExecTime")

	startExecTime, _ := st.(time.Time)

	if initParam.BaseConf.DebugMode == "debug" {
		responseStr := gconv.String(response)
		responseStr = strings.Replace(responseStr, `\`, "", -1)
		//
		v := c.Value("trace")
		traceContext, ok := v.(*lib.TraceContext)
		if !ok {
			traceContext = lib.NewTrace()
		}
		lib.Log.TagInfo(traceContext, "_com_request_out", map[string]interface{}{
			"uri":       c.Request.RequestURI,
			"method":    c.Request.Method,
			"args":      c.Request.PostForm,
			"from":      c.ClientIP(),
			"response":  responseStr,
			"proc_time": endExecTime.Sub(startExecTime).Seconds(),
		})
	}
}

func RequestLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		RequestInLog(c)
		defer func() {
			RequestOutLog(c)
		}()
		c.Next()
	}
}
